package com.example.linktop.chatuidemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private List<ChatMessage> msgList = new ArrayList<>();

    private RecyclerView recyView;
    private MsgAdapter msgAdapter;
    private EditText editText;
    private Button sendBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendBtn = (Button) findViewById(R.id.sendBtn);
        editText = (EditText) findViewById(R.id.editText);
        sendBtn.setOnClickListener(this);

        //初始化聊天
        initializeChat();


        recyView = (RecyclerView) findViewById(R.id.chatRecyView);
        LinearLayoutManager layManager = new LinearLayoutManager(this);
        recyView.setLayoutManager(layManager);
        msgAdapter = new MsgAdapter(msgList);
        recyView.setAdapter(msgAdapter);


    }

    private void  initializeChat() {

        if (msgList == null) {
            msgList = new ArrayList<>();
        }

        for (int i = 0; i < 10; i++) {

            ChatMessage msg = new ChatMessage(""+ i, i%2);
            msgList.add(msg);

        }



    }


    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.sendBtn) {

            String txt = editText.getText().toString().trim();
            if (txt.length() > 0) {
                //更新recyclerview
                ChatMessage msgTmp = new ChatMessage("我是你爸", ChatMessage.MSG_TYPE_SEND);
                msgList.add(msgTmp);
                msgAdapter.notifyItemInserted(msgList.size() - 1);
                recyView.scrollToPosition(msgList.size() - 1);
                editText.setText("");


            } else {

                Toast.makeText(getApplicationContext(), "发送为空", Toast.LENGTH_SHORT).show();
            }


        }


    }
}
